local ETSKSTAT=require'zdc.typetsk'.ETSKSTAT
module(..., package.seeall)


local function get_taskdef(n)
	return {
		ts_create=n.ts_create;
		taction=n.taction;
		targs=n.targs;
		stat=n.stat;
		stat_ts=n.stat_ts;
		runner=n.runner;
	}
end

local function GenKID(n,ts)
	local day=math.floor(ts/(24*3600))
	if n.day < day then
		n.day=day
		n.curid=0
	end
	local cid=(n.curid or 0)+1
	n.curid=cid
	if cid>999999999 then error'order id is out' end
	return string.format("%s-%09d",os.date('%Y%m%d',n.day*24*3600),cid)
end

function AddTask(user,dal,n,act,args)
	local ts=os.time()
	local oid=GenKID(n,ts)
	local child =assert(n:__add_child(oid))
	assert(child('_init', ts,args))
	n.quecnt=n.quecnt+1
	n:__save_ta()
	dal:CommitTA()
	return oid
end

function SetRunner(user,dal,n,act,args)
	local runner=args.runner
	local tskid=args.tskid
	if tskid then
		if not IsParent(n.__id,tskid) then
			return nil,'bad task id'
		end
		local v=dal:GetNode(args.tskid)
		if not v then return nil,'no such task' end
		local r={tskid=v.__id,taskdef=get_taskdef(v)}
		if runner then
			v.runner=runner
			v.stat=ETSKSTAT.ready
			v.stat_ts=ts
			v:__save_ta()
			n.quecnt=n.quecnt-1
			n:__save_ta()
			dal:CommitTA()
		end
		return r
	else
		local cn,lst=dal:GetChildNodesEx(n.__id,'AND(EQ(runner,0),EQ(stat,1))','ik',args.maxcnt or 1)
		local rt={}
		local ts=os.date()
		for i,k in ipairs(lst) do
			local v=cn[k]
			table.insert(rt,{tskid=v.__id,taskdef=get_taskdef(v)})
			if runner then
				v.runner=runner
				v.stat=ETSKSTAT.ready
				v.stat_ts=ts
				v:__save_ta()
			end
		end
		if runner then
			n.quecnt=n.quecnt-#lst
			n:__save_ta()
			dal:CommitTA()
		end
		return rt
	end
end
--------------- task action -------------
function init_task(user,dal,n,act,ts,args)
	local param=args.taction
	if param then
		n.taction=param
	end
	param=args.targs
	if param then
		n.targs=param
	end
	n.stat=ETSKSTAT.queue
	n.stat_ts=ts
	n.ts_create = ts
	n:__set_ik(ts)
	n:__save_ta()
end

function SetStat(user,dal,n,act,args)
	if args.stat then
		n.stat=args.stat
		n.stat_ts=os.date()
		if args.msg then
			n.log=n.log..'\n'..args.msg
		end
		if args.unlock then
			n.runner=0
		end
		n:__save_ta()
		dal:CommitTA()
	end
	return true
end

